﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Microsoft.Reputation.Tests.FrontEndCommon
{
    public partial class ReputationCategory
    {
        public static ReputationCategory ReadToCategory(string rawReputation)
        {
            if (String.IsNullOrEmpty(rawReputation))
            {
                return null;
            }
            string[] pieces = rawReputation.Split(':');
            return new ReputationCategory()
            {
                CategoryId = Int32.Parse(pieces[0]),
                Confidence = Int32.Parse(pieces[1]),
                HostInheritance = Int32.Parse(pieces[2]) == 1,
                PathInheritance = Int32.Parse(pieces[3]) == 1
            };
        }

        public static ReputationCategory Unpack(byte[] packedReputation)
        {
            return ReputationCategory.Unpack(packedReputation, 0);
        }

        public static ReputationCategory Unpack(byte[] packedReputation, int startingOffset)
        {
            byte[] cat = packedReputation.Skip(startingOffset).Take(4).Reverse().ToArray();
            int categoryInfo = BitConverter.ToInt32(cat, 0);
            if (((int)CategoryFlags.NoConf & categoryInfo) == 0)
            {
                return null;
            }
            CategoryFlags catFlags = CategoryFlags.FlagsMask & (CategoryFlags)categoryInfo;
            ConfidenceValues confidence = (catFlags & CategoryFlags.NoConf) == CategoryFlags.NoConf ? ConfidenceValues.None :
                (catFlags & CategoryFlags.NegativeConf) == CategoryFlags.NegativeConf ? ConfidenceValues.Negative : ConfidenceValues.Positive;

            return new ReputationCategory()
            {
                CategoryId = categoryInfo & (int)CategoryFlags.CategoryMask,
                Confidence = (int)confidence,
                HostInheritance = (catFlags & CategoryFlags.HostInherits) == CategoryFlags.HostInherits,
                PathInheritance = (catFlags & CategoryFlags.PathInherits) == CategoryFlags.PathInherits
            };
        }
    }
}
